#include "World.hpp"

#include "Utils.hpp"

World::World() {
    currentLevel = 0;
    levels.push_back("data/levels/test.txt");
    levels.push_back("data/levels/ice.txt");
    levels.push_back("data/levels/level2.txt");
    resetPlayerPosition();
}

World::~World() {
}

bool World::load()
{
    bool bResult = true;

    std::vector<std::string>::iterator it = levels.begin();

    while(it!=levels.end()){
        bResult &=m_lvlLoader.load((*it));
        it++;
    }
    //--editor -f data/levels/level2.txt
    return bResult;
}

int World::goToNextLevel(){
    if(currentLevel < levels.size()-1){
        resetPlayerPosition();
        currentLevel++;
        return currentLevel;
    }
    currentLevel = 0;
    return -1;
}

void World::update() {
    Level currentLvl = getCurrentLevel();

    int floor = player().floor();

    if ( floor >= 0 && floor < currentLvl.floorCount() ) {
        int tileType = currentLvl.getTile(floor, Utils::normaliseAngle(player().angle())/(360.f / currentLvl.angleCount(floor)));
        if ( currentLvl.isHole(tileType) ) {
            // si le player n'est pas en train de sauter
            if ( player().state() != GameObject::JUMP ) {
                setPlayerState(GameObject::FALL);
            }

        }

        if ( player().state() == GameObject::JUMP ) {
            tileType = currentLvl.getTile(floor, Utils::normaliseAngle(player().angle())/(360.f / currentLvl.angleCount(floor)));
            // si le joueur est arrivé un peu haut
            if ( ((int) player().distance() % 50) < 10 ) {
                // si le joueur n'a pas un trou au dessus de sa tete
                if ( !currentLvl.isHole(tileType) ) {
                    setPlayerState(GameObject::BACK_TO_GROUND);
                }
            }
        }

        //if ( player().state() == GameObject::JUMP ) {
            //tileType = currentLvl.getTile(floor-1, Utils::normaliseAngle(player().angle())/(360.f / currentLvl.angleCount(floor)));
            //if ( currentLvl.isWall(tileType) ) {
                //resetPlayerPosition();
            //}
        //}
        //else {
            //if ( currentLvl.isWall(tileType) ) {
                //resetPlayerPosition();
            //}
        //}
    }

    m_player.update();
}

const Player& World::player() const {
    return m_player;
}

void World::setPlayerState(GameObject::State state)
{
    m_player.setState(state);
}

void World::resetPlayerPosition(){
    m_player.setAngle(120);
    m_player.setDistance(340);
    m_player.setState(GameObject::MOVE);
}

const Level& World::getCurrentLevel()const
{
    return m_lvlLoader.getLevel(levels[currentLevel]);
}
